package com.watson.nettydemo.demo02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * // todo
 *
 * @author: llun
 * @date: 2022/3/11 14:46
 * @version: 1.0
 */
public class SocketServer {
    public static void main(String[] args) {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childLoopGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(parentGroup, childLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 字符串解码器  ===》byteBuf
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            // 字符串解码器  ===》byteBuf
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new SocketServerHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.bind(6666).sync();
            System.out.println("服务器已启动");
            sync.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            parentGroup.shutdownGracefully();
            childLoopGroup.shutdownGracefully();
        }


    }
}
